<template>
  <div id="app">
    <el-container style="height: 100%;">
      <!-- 最顶部 -->
      <div class="top_login">
        <ul>
          <li v-if="!$store.state.user">
            <el-button type="text" @click="login">登录</el-button>
            <span>|</span>
            <el-button type="text" @click="register">注册</el-button>
            <!-- 注册表单嵌套 -->
            <el-dialog title="注册" :visible.sync="register_dialogFormVisible" width="30%" center>
              <el-form :model="register_form" :rules="registerFormRules" ref="register_form">
                <el-form-item prop="userName">
                  <el-input
                    placeholder="请输入账号"
                    prefix-icon="el-icon-user-solid"
                    v-model="register_form.userName"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input
                    type="password"
                    placeholder="请输入密码"
                    prefix-icon="el-icon-view"
                    v-model="register_form.password"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="confirmPass">
                  <el-input
                    type="password"
                    placeholder="请再次输入密码"
                    prefix-icon="el-icon-view"
                    v-model="register_form.confirmPass"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    @click="on_register"
                    type="primary"
                    size="medium"
                    style="width: 100%"
                  >注册</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>
            <!-- 注册表单嵌套 -->
          </li>
          <li v-else>
            欢迎
            <el-button type="text" @click="out_visible = true">{{ $store.state.user.userName }}</el-button>
            <!-- 弹出框 -->
            <el-popover placement="top" width="180" v-model="out_visible">
              <p>确定退出登录吗？</p>
              <div style="text-align: right; margin: 10px 0 0">
                <el-button size="mini" type="text" @click="out_visible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="login_out">确定</el-button>
              </div>
            </el-popover>
          </li>
          <li>
            <router-link to="/orders">我的订单</router-link>
          </li>
          <li>
            <router-link to="/Collection">我的收藏</router-link>
          </li>
          <li :class="getNum > 0 ? 'shopCart-full' : 'shopCart'">
            <router-link to="/shoppingCart">
              <i class="el-icon-shopping-cart-full"></i> 购物车
              <span class="num">(0)</span>
            </router-link>
          </li>
        </ul>
      </div>
      <!-- 登录组件 -->
      <login ref="login"></login>
      <el-header>
        <!-- 首页 -->
        <el-menu
          :default-active="$route.path"
          class="el-menu-demo"
          mode="horizontal"
          active-text-color="#409eff"
          router
        >
          <div class="logo">
            <router-link to="/">
              <img src="./assets/imgs/logo.png" alt />
            </router-link>
          </div>
          <el-menu-item index="/">首页</el-menu-item>
          <el-menu-item index="/goods">全部商品</el-menu-item>
          <el-menu-item index="/about">关于我们</el-menu-item>

          <div class="search">
            <el-input placeholder="请输入搜索内容" v-model="search">
              <el-button slot="append" icon="el-icon-search" @click="search_data"></el-button>
            </el-input>
          </div>
        </el-menu>
      </el-header>
      <el-main>
        <keep-alive>
          <router-view></router-view>
        </keep-alive>
      </el-main>
      <el-footer>
        <div class="footer">
          <div class="ng-promise">
            <p class="text">
              <a class="icon1" href="javascript:;">7天无理由退换货</a>
              <a class="icon2" href="javascript:;">满99元全场免邮</a>
              <a class="icon3" style="margin-right: 0" href="javascript:;">100%品质保证</a>
            </p>
          </div>
          <div class="github">
            <div class="github-but"></div>
          </div>
          <div class="mod_help">
            <p>
              <router-link to="/">首页</router-link>
              <span>|</span>
              <router-link to="/">全部商品</router-link>
              <span>|</span>
              <router-link to="/">关于我们</router-link>
            </p>
            <p class="coty">商城版权所有 &copy; 2012-2021</p>
          </div>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>
<script>
import usersAPI from "@/request/api/usersAPI";
import shoppingCartAPI from "./request/api/shoppingCartAPI";
import { mapGetters, mapMutations } from "vuex";
export default {
  data() {
    // 用户名正则字母开头,长度5-16之间,允许字母数字下划线
    const reg = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
    // 用户名校验
    let valid_name = (rule, value, callback) => {
      if (value === "") {
        return callback(new error("请输入用户名"));
      }
      if (reg.test(value)) {
        // 通过正则后端校验
        usersAPI.findUserName({ userName: value }).then((res) => {
          if (res.data.code !== "001") {
            return callback(new Error(res.data.msg));
          } else {
            callback();
          }
        });
      } else {
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };
    // 密码校验
    let valid_password = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入密码"));
      }
      if (!reg.test(value)) {
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
      callback();
    };
    // 重新输入密码校验
    let valid_password2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.register_form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      getNum: 0, //购物车数量
      search: "", // 搜索
      out_visible: false,
      // 注册表单弹出
      register_dialogFormVisible: false,
      // 注册表单
      register_form: {
        userName: "",
        password: "",
        confirmPass: "",
      },
      // 验证
      registerFormRules: {
        userName: [{ validator: valid_name, trigger: "blur" }],
        password: [{ validator: valid_password, trigger: "blur" }],
        confirmPass: [{ validator: valid_password2, trigger: "blur" }],
      },
    };
  },
  created() {
    // 获取本地存储信息
    let userInfo = window.localStorage.getItem("user");
    if (userInfo) {
      //调用vuex中的setUser方法重新存储用户信息
      this.setUser(JSON.parse(userInfo));
    }
  },
  methods: {
    ...mapMutations(["setUser", "setShowLogin"]),
    // 点击搜索按钮
    search_data() {
      console.log("当前搜索的内容", this.search);
      // 去除字符串前后空格
      let search_str = this.search.trim();
      this.search = "";
      // 跳转传参
      this.$router.push({
        path: "/goods",
        query: {
          search: search_str,
        },
      });
    },
    // 点击注册按钮弹出
    register() {
      this.register_dialogFormVisible = true;
    },
    // 注册表单确定
    on_register() {
      this.$refs.register_form.validate(async (valid) => {
        console.log(valid);
        if (valid) {
          let { data: res } = await usersAPI.register({
            userName: this.register_form.userName,
            password: this.register_form.password,
          });
          console.log(res);
          if (res.code == "001") {
            this.$notify({
              title: "成功",
              message: res.msg,
              type: "success",
            });
            this.register_dialogFormVisible = false;
          } else {
            this.$notify.error({
              title: "错误",
              message: res.msg,
            });
          }
        }
      });
    },
    //点击登录
    login() {
      this.setShowLogin(true);
    },
    //获取购物车信息
    async getShoppingCart(userId) {
      let { data: res } = await shoppingCartAPI.getShoppingCart({
        user_id: userId,
      });
      // code: "401"
      // msg: "用户没有登录，请登录后再操作"
      if (res.code !== "001") {
        //可能cookie过期
        //清空本地登录信息
        window.localStorage.clear();
        //清空vuex中的用信息
        this.setUser(null);
        //提示用户重新登录
        this.$notifyError(res.msg);
      } else {
        res.shoppingCartData.forEach((item) => {
          this.getNum += item.num;
        });
        this.$store.dispatch("setShopCart", res.shoppingCartData);
        // 将购物车的信息保存在vuex中，通过触发dispatch异步action
      }
    },
    //退出登录
    login_out() {
      localStorage.setItem("user", "");
      this.out_visible = false;
      this.$notify({
        title: "成功",
        message: "退出登录成功",
        type: "success",
      });
      // 刷新页面
      location.reload();
    },
  },
  computed: {
    ...mapGetters(["userInfo", "userName"]),
  },
  watch: {
    userInfo(value) {
      if (value) {
        this.getShoppingCart(value.user_id);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  list-style: none;
}

#app {
  height: 100%;
}

body > .el-container {
  margin-bottom: 40px;
}

// 下划线
a,
a:hover {
  text-decoration: none;
}

// 顶部
.top_login {
  height: 40px;
  background-color: #3d3d3d;
  margin-bottom: 20px;
  color: #b0b0b0;
  ul {
    float: right;
    margin-right: 160px;
  }
  li {
    float: left;
    height: 40px;
    font-size: 14px;
    text-align: center;
    line-height: 40px;
    margin-left: 20px;
    .el-button--text {
      color: #b0b0b0;
    }
    a {
      color: #b0b0b0;
    }
  }
}

// hearder
.el-header {
  width: 100%;
  height: 200px;
  background-color: #fff;
  .el-menu {
    max-width: 1225px;
    margin: 0 auto;
  }
  .logo {
    height: 60px;
    width: 189px;
    float: left;
    margin-right: 100px;
  }
  .search {
    margin-top: 10px;
    width: 300px;
    float: right;
  }
}

.el-main {
  background-color: #fff;
  color: #333;
  text-align: center;
  height: 100%;
}

.el-footer {
  background-color: #2f2f2f;
  padding: 0;
  color: #fff;
  text-align: center;
  .footer {
    background-color: #2f2f2f;
    .ng-promise p a {
      color: #fff;
      font-size: 20px;
      margin-right: 210px;
      padding-left: 44px;
      height: 40px;
      display: inline-block;
      line-height: 40px;
      background: url("./assets/imgs/us-icon.png") no-repeat left 0;
    }
    .text {
      margin-top: 20px;
      margin-bottom: 20px;
    }
    .github {
      height: 50px;
      line-height: 50px;
      margin-top: 20px;
    }
    .github .github-but {
      width: 50px;
      height: 50px;
      margin: 0 auto;
      background: url("./assets/imgs/github.png") no-repeat;
    }
    .mod_help {
      text-align: center;
      color: #888888;
    }
    .mod_help p {
      margin: 20px 0 16px 0;
    }
    .mod_help p a {
      color: #888888;
      text-decoration: none;
    }
    .mod_help p a:hover {
      color: #fff;
    }
    .mod_help p span {
      padding: 0 22px;
    }
  }
}
// 加入购物车
.shopCart-full {
  width: 120px;
  background: #ff6700;
  color: #ffffff;
  a {
    color: white;
  }
}
.shopCart {
  width: 120px;
  background: #424242;
}
.shopCart:hover {
  background: #fff;
}
.shopCart:hover a {
  color: #ff6700;
}
</style>
